<template>
  <div class="release">
    <div class="top">
      <van-nav-bar title="发布" />
    </div>
    <div class="main">
      <van-form @submit="onSubmit">
        <van-field
          v-model="title"
          class="title"
          name="title"
          placeholder="请输入标题"
        />

        <van-field
          class="content"
          v-model="content"
          name="content"
          rows="2"
          type="textarea"
          placeholder="请输入内容"
          show-word-limit
        />
        <van-field v-model="type" name="type" placeholder="请输入类型" />
        <van-field name="imageSrc" class="updata">
          <template #input>
            <van-uploader
              :after-read="afterRead"
              :max-count="2"
              v-model="Src"
            />
          </template>
        </van-field>
        <div style="margin: 16px">
          <van-button
            color="rgb(7,193,96)"
            block
            type="info"
            native-type="submit"
            @change="onSubmit"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { Uploader } from "vant";
export default {
  data() {
    return {
      title: "",
      content: "",
      Src: [],
      type: "",
      cate_id: "",
      calss: [],
      imageSrc: [],
      img: [],
    };
  },
  components: {
    [Uploader.name]: Uploader,
  },
  methods: {
    afterRead() {
      // 此时可以自行将文件上传至服务器
      // console.log(file);
      this.Src.map((v) => {
        this.imageSrc.push(this.upload(v));
      });
      Promise.all(this.imageSrc).then((res) => {
        // console.log(res);
        this.img = res;
      });
    },
    async onSubmit(values) {
     let dd= await this.getclass();
console.log('这是'+dd);
      let cate_id =dd
   
      let userInfo = localStorage.getItem("tt-userInfo");
      userInfo = JSON.parse(userInfo);
      let author = userInfo.nickname;
      let author_id = userInfo._id;
      let title = this.title;
      let content = this.content;
      let imageSrc = this.img;
      // console.log('1'+imageSrc);
      this.$http
        .post("/api/add_article", {
          cate_id,
          author,
          author_id,
          title,
          content,
          cate_name: this.type,
          imageSrc,
        })
        .then((res) => {
          console.log(res);
          if (res.code==0) {
            this.$toast('发布成功')
          }
        });
      console.log(author);
      console.log(author_id);
      console.log(title);
      console.log(content);

    },
    // 分类
    getclass() {
      return this.$http.post("/api/get_cate_list").then((res) => {
        // console.log(res);
        if (res.code == 0) {
          this.class = res.data;
          // console.log(this.class);
          let newClass = [];
          let item;
          let aa;
          for (let i = 0; i < this.class.length; i++) {
            // console.log(this.class[i]);
            // console.log(this.class[i].name);
            newClass.push(this.class[i]);
          }

          while (newClass.length - 1) {
            item = newClass.shift();
            // console.log(item);
            if (item.name === this.type) {
              aa = item._id;
            return aa;
            }
          }


          // console.log(newClass);
        }
      });
    },

    async upload(e) {
      let file = e.file; // 获取到文件  //
      console.log(file);

      let { type } = file;
      //  拿到类型  比如jpg
      type = type.split("/")[1];
      // 重新命名
      let file_name = `${new Date().getTime()}_${Math.random()
        .toString(36)
        .slice(2)}.${type}`;

      // 去自己的服务器拿到上传七牛云需要的 token  为何放在服务端呢?  主要是为了安全，因为里边包含了一些账号信息

      let { token } = await this.$http.post("/upload/token");

      // new一个form data   并且把文件 token  和文件的名字放进去  file token key是固定的 不能改
      const formdata = new FormData();
      formdata.append("file", file);
      formdata.append("token", token);
      formdata.append("key", file_name);

      // https://upload-z1.qiniup.com 是上传到七牛的真正接口  其中z1是华北区域

      let result = await this.$http.post(
        "https://upload-z1.qiniup.com",
        formdata
      );
      console.log(result);
      console.log(`http://toutiao.longxiaokj.com/` + result.key);
      return `http://toutiao.longxiaokj.com/` + result.key;
      // `http://toutiao.longxiaokj.com/` + result.key  这个地址就是传到服务器的地址
      // 发布文章时 imageSrc  字段需要的就是这个
    },
  },
};
</script>

<style lang="scss" scoped>
.release {
  height: 100vh;
  background-color: rgb(245, 247, 249);
  .title {
    margin-top: 10px;
  }
  .content {
    margin: 10px 0;
  }
  .updata {
    padding: 0 16px;
    background-color: rgb(245, 247, 249);
    border: none;
  }
  .van-cell::after {
    border: none;
  }
}
</style>